﻿using BackData;
using CSRedis;
using Details.API.Application.Command;
using Details.API.DTOs;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using NetTaste;
using Newtonsoft.Json.Linq;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Details.API.Controllers
{
    /// <summary>
    /// 用户登录控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
   // [Authorize]
    public class UsersController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IConfiguration configuration;
        private readonly CSRedisClient cSRedisClient;

        public UsersController(IMediator mediator, IConfiguration configuration, CSRedisClient cSRedisClient )
        {
            this.mediator = mediator;
            this.configuration = configuration;
            this.cSRedisClient = cSRedisClient;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request">账号,密码</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>用户信息</returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        [AllowAnonymous]
        public Task<APIResult<UserDTO>> UserLogin([FromQuery] UserLoginCommand request)
        {
            return mediator.Send(request);
        }


        /// <summary>
        /// 测试JWT
        /// </summary>
        [HttpPost]

        public IActionResult TestJWT()
        {
            return Ok("测试成功");
        }
        /// <summary>
        /// 刷新 Token, 返回新的 Token
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public string RefreshToken(string RefreshToken)
        {
            var res = cSRedisClient?.Get(RefreshToken);  //获取存在redis里的值
  
            if (!string.IsNullOrEmpty(res))  //值存值
            {
               return CreateTokenString(res, TimeSpan.FromMinutes(20));  //短期Token创建      
            }
            else  //值不存在
            {
                return "Token已过期,请用户重新登录,马上为您跳转到登录页面";
            }
        }
        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <param name="RealName">荷载</param>
        /// <param name="expires">过期时间</param>
        /// <returns></returns>
        private string CreateTokenString(string RealName, TimeSpan? expires)
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(configuration["JWT:key"]);  //配置文件自定义私钥
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] {
                new Claim("RealName" ,RealName)  //真实姓名放入荷载
            };
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: configuration["JWT:issuer"], //     配置文件自定义发布者
                audience: configuration["JWT:audience"],  //  配置文件自定义订阅
                expires: DateTime.UtcNow.Add(expires.Value), // 传参自定义过期时间
                signingCredentials: signingCredentials,
                claims: claims  // 荷载
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
